<template>
  <div id="asn" v-loading="loading">
    <v-tableTitle :btnConfig="btnConfig" :tableSelectData="tableSelectData" :title="$t('in.asn')" @allReception="allReception" @closeAsn="closeAsn" @del="del" @printasn="printasn"
      @exportAsn="exportAsn" @generate="generate" @generatePing="generatePing" @mScanGather="mScanGather" @mScanRetreat="mScanRetreat" @newActivation="newActivation" @newCreate="newCreate"
      @scanGather="scanGather" @scanRetreat="scanRetreat" @receivingrotation="receivingrotation" @handleDownErrorFile="exceptionFileUrl" @handleDownTemplate="downloadExcelFile"></v-tableTitle>
    <GTable ref="table" :hasCheck="true" :hasEdit="true" api="queryAllReceiptList" :otherHeight="0" dateKey="adddate" :showSummary="true" :columnConfig="columnConfig" @selection-change="selectData"
      @setdialog="setdialog">
    </GTable>
  </div>
</template>

<script type="text/ecmascript-6">
import drawer from './deawer/Deawer'
import tableTitle from 'commons/TableTitle'
import table from 'commons/Table'
import baseMixin from '@/mixins/BaseMixin'
import config from './Config'
import print from '@/assets/js/print'
import agGridBaseMixin from '@/mixins/AgGridBaseMixin'

export default {
  name: 'asn',
  mixins: [baseMixin, config, agGridBaseMixin],
  data() {
    return {
      loading: false,
      columnConfig: { menu_id: 17, menu_code: 'asn', menu_list_code: 'ASN' },
      tableSelectData: []
    }
  },
  computed: {
    btnConfig() {
      return [
        {
          type: 'file',
          certigier:
            this.uploadStatus || !this.btnPermNameList.includes('WM010101'),
          label: this.$t('common.import'),
          invalid: 'file',
          importType: '10309',
          importUrl: 'importAsn',
          downTemplate: 'handleDownTemplate',
          sheetKey: 'receiptDetailList'
        },
        // {label: this.$t('config.importTemDownload'), certigier: this.poiStatus||!this.btnPermNameList.includes('WM010102'), invalid: "downloadExcelFile"},
        {
          label: this.$t('common.export'),
          certigier:
            this.downloadStatus || !this.btnPermNameList.includes('WM010103'),
          disabled: true,
          invalid: 'exportAsn'
        },
        {
          label: this.$t('common.create'),
          certigier:
            this.newStatus || !this.btnPermNameList.includes('WM010104'),
          invalid: 'newCreate'
        },
        {
          label: this.$t('common.print'),
          certigier:
            this.deleteStatus || !this.btnPermNameList.includes('WM010105'),
          disabled: true,
          invalid: 'printasn'
        },
        {
          type: 'more',
          label: this.$t('common.moreMenu'),
          certigier: !this.btnPermNameList.includes('WM010106'),
          invalid: 'down',
          btnConfig: [
            {
              label: this.$t('in.allReception'),
              certigier:
                this.actionStatus || !this.btnPermNameList.includes('WM010107'),
              disabled: true,
              invalid: 'allReception'
            },
            {
              label: this.$t('in.newActivation'),
              certigier:
                this.actionStatus || !this.btnPermNameList.includes('WM010108'),
              disabled: true,
              invalid: 'newActivation'
            },
            {
              label: this.$t('in.closeAsn'),
              certigier:
                this.actionStatus || !this.btnPermNameList.includes('WM010109'),
              disabled: true,
              invalid: 'closeAsn'
            },
            {
              label: this.$t('in.scanGather'),
              certigier:
                this.actionStatus || !this.btnPermNameList.includes('WM010110'),
              disabled: true,
              invalid: 'scanGather'
            },
            {
              label: this.$t('in.scanRetreat'),
              certigier:
                this.actionStatus || !this.btnPermNameList.includes('WM010111'),
              disabled: true,
              invalid: 'scanRetreat'
            },
            {
              label: this.$t('in.receivingrotation'),
              certigier:
                this.actionStatus || !this.btnPermNameList.includes('WM010112'),
              disabled: true,
              invalid: 'receivingrotation'
            }
            /*{ label: "生成立库上架", certigier: this.actionStatus, disabled: true, invalid: "generate" },
            { label: "生成平库上架", certigier: this.actionStatus, disabled: true, invalid: "generatePing" },*/
            /*{
              label: "单件盲扫收货",
              certigier: this.blindActionStatus,
              disabled: true,
              invalid: "mScanGather"
            },
            {
              label: "单件盲扫退货",
              certigier: this.blindActionStatus,
              disabled: true,
              invalid: "mScanRetreat"
            }*/
          ]
        }
      ]
    }
  },
  created() {},
  methods: {
    exceptionFileUrl(exceptionUrl) {
      console.log('exceptionFileUrl = %o', exceptionUrl)
      const data = [
        {
          exceptionFileUrl: exceptionUrl
        }
      ]

      // 异常下载配置
      let urlConf = { responseType: 'blob' }
      let exceptionFileName = 'ASN收货单导入模板异常文件.xls'
      let url = '/comExcelImportResult/downloadExceptionFile'
      let options = {
        type:
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'
      }

      try {
        this.$api.post(url, data, urlConf).then(res => {
          let blobParts = [res.data]
          if (window.navigator.msSaveBlob) {
            const blobObject = new Blob(blobParts)
            window.navigator.msSaveBlob(blobObject, exceptionFileName)
          } else {
            let tagName = 'a'
            const blob = new Blob(blobParts, options)
            const downloadElement = document.createElement(tagName)
            // 创建下载的链接
            const href = window.URL.createObjectURL(blob)
            downloadElement.style.display = 'none'
            downloadElement.href = href
            // 下载后文件名
            downloadElement.download = exceptionFileName
            document.body.appendChild(downloadElement)
            // 点击下载
            downloadElement.click()
            // 下载完成移除元素
            document.body.removeChild(downloadElement)
            // 释放掉blob对象
            window.URL.revokeObjectURL(href)
          }
        })
      } catch (e) {
        this.$message.error(e)
      }
    },
    //全部接收
    allReception(data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/asnReceiveAll/${item.receiptkey}`)
          
            this.$message.success(res.returnMgr)
            // this.getTableData(1, {});
            this.$refs.table.delSelectData(item, index)
          
        } catch (e) {
          this.$message.error(e)
        }
      })
    },
    //重新激活ASN/收货单
    newActivation(data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/asnReactivation/${item.receiptkey}`)
          
            this.$message.success(res.returnMgr)
            // this.getTableData(1, {});
            this.$refs.table.delSelectData(item, index)
          
        } catch (e) {
          this.$message.error(e)
        }
      })
    },
    //结算/关闭ASN/收货单
    closeAsn(data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/asnCompleteClose/${item.receiptkey}`)
          
            this.$message.success(res.returnMgr)
            // this.getTableData(1, {});
            this.$refs.table.delSelectData(item, index)
          
        } catch (e) {
          this.$message.error(e)
        }
      })
    },
    //生成立库上架
    generate(data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(
            `/genPutawayTask2/${item.receiptkey}/LKPP`
          )
          
            this.$message.success(res.returnMgr)
            // this.getTableData(1, {});
            this.$refs.table.delSelectData(item, index)
          
        } catch (e) {
          this.$message.error(e)
        }
      })
    },
    //生成ping库上架
    generatePing(data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(
            `/genPutawayTask2/${item.receiptkey}/PKPP`
          )
          
            this.$message.success(res.returnMgr)
            // this.getTableData(1, {});
            this.$refs.table.delSelectData(item, index)
          
        } catch (e) {
          this.$message.error(e)
        }
      })
    },
    //单件扫描收货
    async scanGather(data) {
      let self = this
      if (data.length > 1) {
        self.$message.error(this.$t('msg.msg32'))
      } else {
        if (data[0].status == 9) {
          this.$message.error(this.$t('msg.msg33'))
          return
        }
        if (data[0].status == 11) {
          this.$message.error(this.$t('msg.msg34'))
          return
        }
        if (data[0].status == 15) {
          this.$message.error(this.$t('msg.msg35'))
          return
        }
        if (data[0].status == 20) {
          this.$message.error(this.$t('msg.msg36'))
          return
        }

        let whseid = self.$store.state.wms
        let opeuser = self.$store.state.user
        let receiptkey = data[0].receiptkey
        let name = 'ONESCANNOREGISTER'
        //验证是否可以跳转
        let flag
        await self.$api.get(`/validateUDF1/${receiptkey}`).then(res => {
          
            flag = res.bean
        })
        if (!flag) {
          self.$message.error(self.$t('msg.msg50', { no: data[0].receiptkey }))
        } else {
          try {
            let res = await this.$api.get(`/getHttpUrl/${name}`)
            
              let url = `${res.bean}?whseid=${whseid}&opeuser=${opeuser}&receiptkey=${receiptkey}&benchNo=0001`
              //let url = `http://localhost:8086/rtxext/InitReceiptOneScanPage?whseid=${whseid}&opeuser=${opeuser}&receiptkey=${receiptkey}&benchNo=0001`;
              this.$router.push({
                name: 'iframe',
                params: { url: url, title: '单件扫描收货' }
              })
            
          } catch (e) {
            this.$message.error(e)
          }
        }
      }
    },
    //单件扫描退货
    async scanRetreat(data) {
      let self = this
      if (data.length > 1) {
        this.$message.error(this.$t('msg.msg32'))
      } else {
        if (data[0].status == 9) {
          this.$message.error(this.$t('msg.msg33'))
          return
        }

        if (data[0].status == 11) {
          this.$message.error(this.$t('msg.msg34'))
          return
        }
        if (data[0].status == 15) {
          this.$message.error(this.$t('msg.msg35'))
          return
        }
        if (data[0].status == 20) {
          this.$message.error(this.$t('msg.msg36'))
          return
        }
        let whseid = this.$store.state.wms
        let users = this.$Cookies.get('user')
        let name = 'ONESCANRET'
        let receiptkey = data[0].receiptkey

        //验证是否可以跳转
        let flag
        await self.$api.get(`/validateUDF1/${receiptkey}`).then(res => {
          
            flag = res.bean
        })

        if (flag) {
          self.$message.error(self.$t('msg.msg51', { no: data[0].receiptkey }))
        } else {
          try {
            let res = await this.$api.get(
              `/asnReturnGoods/${receiptkey}/${name}`
            )
            
              let storerKey = res.bean.storerkey
              let externReceiptKey = res.bean.externreceiptkey
              let type = res.bean.type
              try {
                let response = await this.$api.get(`/getHttpUrl/${name}`)
                  let url = `${response.data.bean}?whseid=${whseid}&users=${users}&receiptKey=${receiptkey}&storerKey=${storerKey}&externReceiptKey=${externReceiptKey}&type=${type}`
                  //let url = `http://localhost:8086/rtxext/InitReturnOneScanPage?whseid=${whseid}&users=${users}&receiptKey=${receiptkey}&storerKey=${storerKey}&externReceiptKey=${externReceiptKey}&type=${type}`;
                  this.$router.push({
                    name: 'iframe',
                    params: { url: url, title: '单件扫描退货' }
                  })
              } catch (e) {
                this.$message.error(e)
              }
          } catch (e) {
            this.$message.error(e)
          }
        }
      }
    },
    //收货单件回转
    async receivingrotation(data) {
      if (data.length > 1) {
        this.$message.error(this.$t('msg.msg32'))
      } else {
        /*if (data[0].status == 9) {
          this.$message.error(this.$t('msg.msg33'));
          return
        }*/

        if (data[0].status == 11) {
          this.$message.error(this.$t('msg.msg34'))
          return
        }
        if (data[0].status == 15) {
          this.$message.error(this.$t('msg.msg35'))
          return
        }
        if (data[0].status == 20) {
          this.$message.error(this.$t('msg.msg36'))
          return
        }
        let whseid = this.$store.state.wms
        let opeuser = this.$Cookies.get('user')
        let receiptkey = data[0].receiptkey
        let storerkey = data[0].storerkey
        let name = 'RECEIVINGROTATION'
        try {
          let res = await this.$api.get(`/getHttpUrl/${name}`)
          
            let url = `${res.bean}?whseid=${whseid}&opeuser=${opeuser}&users=${opeuser}&receiptkey=${receiptkey}&storerkey=${storerkey}`
            this.$router.push({
              name: 'iframe',
              params: { url: url, title: '收货单件回转' }
            })
          
        } catch (e) {
          this.$message.error(e)
        }
      }
    },
    //单件盲扫收货
    async mScanGather(data) {
      let whseid = this.$store.state.wms
      let users = this.$Cookies.get('user')
      let name = 'ONESCANNOREGISTER'
      let receiptkey = data[0].receiptkey
      try {
        let res = await this.$api.get(`/asnReturnGoods/${receiptkey}/${name}`)
        
          try {
            let response = await this.$api.get(`/getHttpUrl/${name}`)
            
              let url = `${response.data.bean}?whseid=${whseid}&opeuser=${users}&receiptkey=${receiptkey}&name=${name}`
              this.$router.push({
                name: 'iframe',
                params: { url: url, title: '单件盲扫收货' }
              })
          } catch (e) {
            this.$message.error(e)
          }
        
      } catch (e) {
        this.$message.error(e)
      }
    },
    //单件盲扫退货
    async mScanRetreat(data) {
      let whseid = this.$store.state.wms
      let users = this.$Cookies.get('user')
      let name = 'BLINDONESCANRET'
      let receiptkey = data[0].receiptkey
      try {
        let res = await this.$api.get(`/asnReturnGoods/${receiptkey}/${name}`)
        
          let storerKey = res.bean.storerkey
          let externReceiptKey = res.bean.externreceiptkey
          try {
            let response = await this.$api.get(`/getHttpUrl/${name}`)
              let url = `${response.data.bean}?whseid=${whseid}&users=${users}&receiptKey=${receiptkey}&storerKey=${storerKey}&externReceiptKey=${externReceiptKey}&name=${name}`
              this.$router.push({ name: 'iframe', params: { url: url } })
          } catch (e) {
            this.$message.error(e)
          }
        
      } catch (e) {
        this.$message.error(e)
      }
    },
    //新建
    async newCreate() {
      this.$router.push({ name: 'asnDeawer', query: { newFlag: true } })
      // try {
      //   // let res = await this.$api.get("/codeLookup/nCounter/RECEIPT");
      //   // 2022-10-28 修改单号编码取值方式 hkjun
      //   let numberType = 11702;
      //   let res = await this.$api.get("/sysNumberRule/getSysNumberByType/"+numberType);
      //   
      //     this.$store.commit("setRouteId", res.data.data);
      //     this.$store.commit("setRouteData", {});
      //     this.$store.commit("setNewFlag", true);
      //     this.$router.push({ name: "asnDeawer"});
      //   }
      // } catch (e) {
      //   this.$message.error(e);
      // }
    },
    // 导出
    async exportAsn (data) {
      try {
        let res = await this.$api.post("/asn/exportAsn", data, { responseType: "blob" });
        if (window.navigator.msSaveBlob) {
          var blobObject = new Blob([res.data]);
          window.navigator.msSaveBlob(blobObject, "asn.xls");
        } else {
          var blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8" });
          var filename = "ans.xls";
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.style.display = "none";
          downloadElement.href = href;
          downloadElement.download = filename; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }
      } catch (e) {
        this.$message.error(e);
      } finally {
        
      }
    },
    async downloadExcelFile(data) {
      try {
        let xlsName = 'ASN收货单导入模板.xls'
        let url = '/downloadExcelFile/' + xlsName
        let res = await this.$api.post(url, {}, { responseType: 'blob' })
        if (window.navigator.msSaveBlob) {
          var blobObject = new Blob([res.data])
          window.navigator.msSaveBlob(blobObject, xlsName)
        } else {
          var blob = new Blob([res.data], {
            type:
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'
          })
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.style.display = 'none'
          downloadElement.href = href
          downloadElement.download = xlsName //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        }
      } catch (e) {
        this.$message.error(e)
      }
    },
    //导入
    async upFileBak(data) {
      try {
        let res = await this.$api.post('/asn/importAsn', data)
          this.$message.success(res.returnMgr)
      } catch (e) {
        this.$message.error(e)
      }
    },
    //选中的内容
    selectData(data) {
      this.tableSelectData = data
    },
    //删除
    del(data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.delete(`/asn/${item.receiptkey}`)
          
            this.$message.success(res.returnMgr)
            // let page = sessionStorage.getItem("page");
            // this.getTableData(page, this.tableSearhData);
            this.$refs.table.delSelectData(item, index)
        } catch (e) {
          this.$message.error(e)
        }
      })
    },
    printasn(data) {
      data.forEach(async (item, index) => {
        try {
          // print.birtprint("SHCYD","receiptkey=" + item.receiptkey);
          print.grfprint('SHCYD', item.receiptkey)
        } catch (e) {
          this.$message.error(e)
        }
      })
    },

    //搜索的值
    searhData(data, up) {
      if (!up) {
        this.tableSearhData = data
      } else {
        this.tableSearhData = data
        // this.getTableData(1, this.tableSearhData);
      }
    },
    //设置弹框
    setdialog(data) {
      // this.$store.commit("setRouteData", data);
      this.$router.push({ name: 'asnDeawer', query: data })
    }
  },
  mounted() {
    // ;
    this.$store.commit('setSkip', {})
    this.$store.commit('setRouteId', '')
    this.$store.commit('setNewFlag', false)
    this.$store.commit('setRouteData', {})
    this.$store.commit('setTemporary', '')
    // this.getTableData(1, {});
  },
  watch: {
    tableSelectData(data) {
      if (this.permissionStatus) {
        if (data.length > 0) {
          this.deleteStatus = this.downloadStatus = this.actionStatus = this.blindActionStatus = false
        } else {
          this.deleteStatus = this.downloadStatus = this.actionStatus = this.blindActionStatus = true
        }
      }
    }
  },
  components: {
    'v-tableTitle': tableTitle,
    'v-table': table,
    'v-drawer': drawer
  }
}
</script>

<style scoped>
#asn {
  width: 100%;
  height: 99%;
  padding-top: 6px;
}
</style>
